<template>
    <div>
        <!--<button v-if="showGetUserInfoButton" class="zan-btn zan-btn--primary" open-type="getUserInfo" @getuserinfo="bindGetUserinfo">授权登录</button>-->
        <!--<div class="zan-row" v-if="user.is_vip !== 'Y'">
            <div class="zan-col zan-col-12">
                <div class="mem_btn" @click="handleMemberCard">绑定会员卡</div>
            </div>
            <div class="zan-col zan-col-12">
                <div class="mem_btn" style="border-left:1px solid white;">申请会员卡</div>
            </div>
        </div>-->
        <!-- <button @click="addWxCard">获取微信会员卡1</button> -->
        <!-- <button @click="addWxCard">发送模板消息</button> -->

        <!-- <button @click="skip">跳转</button> -->
        <!-- <div class="card" style="background-image: url('https://wechat-uploads.oss-cn-hangzhou.aliyuncs.com/card.jpg')"> -->
        <!-- <div class="card" style="background-color:'{{color}}'"> -->
        <div class="card" :style="styles1">
            <div class="card-num">
                <div v-if="user.card_no">{{user.card_tpl_name}} {{user.card_no}}</div>
                <div v-else>{{user.name}}</div>
            </div>
            <div class="addcard-btn" @click="handleBindCard" v-if="!user.card_no">
              <div>绑定会员卡</div>
            </div>
            <!--<div class="addcard-btn" @click="addWxCard" v-if="!user.card_id">-->
              <!--<div>领取微信会员卡</div>-->
            <!--</div>-->
        </div>
        <div class="zan-row user">
            <div class="zan-col zan-col-8 userInfo">
                <div>余额</div>
                <div v-if="user.balance>0">{{user.balance/100}}</div>
                <div v-else>0</div>
            </div>
            <div class="zan-col zan-col-8 userInfo">
                <div>积分</div>
                <div v-if="user.points>0">{{user.points}}</div>
                <div v-else>0</div>
            </div>
            <div class="zan-col zan-col-8 userInfo" hover-class="grid_active" @click="hanldeCoupons">
                <div class="coupons">优惠券<span class="zan-arrow arrow"></span></div>
                <div>{{coupons_num}}</div>
            </div>
        </div>
        <div class="grids">
            <div v-for="(item,index) in list" :key="index" class="grids-item" hover-class="grid_active"
                 @click="handleGrid(item)">
                <div class="zan-icon" :class="'zan-icon-' + item.icon" style="color: #292929;"></div>
                <div class="grid_label">{{item.name}}</div>
            </div>
        </div>
        <div v-if="showGetUserInfoButton" class="dialog-box">
            <div class="dialog-body">
                <div style="height:40px;line-height:40px;border-bottom: 1px solid #DBDBDB;text-align:center;">授权登录</div>
                <div style="padding: 15px 10px;font-size:14px;color:#838B83;">系统需要获取您的头像和昵称等信息</div>
                <div>
                    <button class="confirm-btn" open-type="getUserInfo" @getuserinfo="bindGetUserinfo">同意</button>
                    <button class="cancel-btn" @click="handleCancel">取消</button>
                </div>
            </div>
        </div>
        <!--<official-account></official-account>-->
        <!-- <button @click="clean">清除数据</button>
        <button @click='activeWxCard'>激活会员卡</button> -->
        <!-- <button @click='receipt'>收款</button> -->
        <!-- <button @click='check_in'>签到</button> -->
        <!-- <button @click="navigateTo('sale_cards?scene=2')">售卡</button> -->
        <!-- <button @click="navigateTo('../home/order_detail')">订单详情</button> -->
        <!-- <form @submit="testSubmit" report-submit="true">
            <button formType="submit">发送模板消息</button>
        </form> -->
        <button @click="navigateTo('../activity/kanjia')">砍价11</button>
        <!-- <button @click="navigateTo('../activity/kanjia_record?active=1')">砍价记录</button>
        <button @click="navigateTo('../activity/kanjia_detail?order_id=11')">砍价详情</button> --> 
    </div>
</template>

<script>
    import api from '@/utils/api'
    import {showErrorMsg} from '@/utils/showToast'
    import {mapGetters} from 'vuex'
    var colors = [{
        "name": "Color010",
        "value": "#63b359"
      },
      {
        "name": "Color020",
        "value": "#2c9f67"
      },
      {
        "name": "Color030",
        "value": "#509fc9"
      },
      {
        "name": "Color040",
        "value": "#5885cf"
      },
      {
        "name": "Color050",
        "value": "#9062c0"
      },
      {
        "name": "Color060",
        "value": "#d09a45"
      },
      {
        "name": "Color070",
        "value": "#e4b138"
      },
      {
        "name": "Color080",
        "value": "#ee903c"
      },
      {
        "name": "Color081",
        "value": "#f08500"
      },
      {
        "name": "Color082",
        "value": "#a9d92d"
      },
      {
        "name": "Color090",
        "value": "#dd6549"
      },
      {
        "name": "Color100",
        "value": "#cc463d"
      },
      {
        "name": "Color101",
        "value": "#cf3e36"
      },
      {
        "name": "Color102",
        "value": "#5E6671"
      }
    ]

    export default {
        data() {
          return {
            showModalStatus: false,
            list: [
              {icon: 'qr', name: '付款码', url: 'pay_code'},
              {icon: 'wechat', name: '微信充值', url: 'wechat_recharge'},
              {icon: 'pending-orders', name: '领券中心', url: 'coupon_center'},
              {icon: 'points-mall', name: '积分商城', url: 'points_mall'},
              {icon: 'receive-gift', name: '签到', url: 'check_in'},
              {icon: 'contact', name: '会员信息', url: 'member_info'},
              {icon: 'edit', name: '交易记录', url: 'transaction_record'},
              {icon: 'setting', name: '修改密码', url: 'modify_password'},
              {icon: 'pending-evaluate', name: '意见反馈', url: 'feedback'},
              {icon: 'description', name: '会员说明', url: 'description'},
              {icon: 'send-gift', name: '邀请有奖', url: 'invitation'},
              {icon: 'receive-gift', name: '新人礼包', url: 'new_user_gifts'},
              {icon: 'gift-card', name: '礼品卡', url: 'gift_card/gift_card'},
              // {icon: 'card', name: '微信会员卡', url: 'wechat_card'},
            ],
            canIUse: wx.canIUse('button.open-type.getUserInfo'),
            showGetUserInfoButton: false,
            form_id:'',
            color:'#d09a45'
          }
        },
        computed: {
          ...mapGetters([
              'user',
              'user_status',
              'login_info',
              'coupons_num',
          ]),
          styles1() {
            // console.log('styles1',this.user)
            if(this.user.background_pic_url){
              // console.log('styles1',1)
              return "background-image:url('"+this.user.background_pic_url+"')"
            }
            if(this.user.background_pic_url2){
              // console.log('styles1',1)
              return "background-image:url('"+this.user.background_pic_url2+"')"
            }
            if(this.user.color){
              // console.log(colors)
              let color=''
              colors.forEach(item=>{
                if(item.name==this.user.color){
                  color=item.value
                }
              })
              return "background-color:"+color
            }
            return "background-image: url('https://wechat-uploads.oss-cn-hangzhou.aliyuncs.com/card.jpg')"
          }
        },
        beforeMount() {
          // let um=wx.getUpdateManager()
        },
        mounted() {
          wx.getSetting({
            success(res) {
              if (!res.authSetting['scope.userInfo']) {
                let url = 'get_user_info?callback_url=../user/index'
                wx.navigateTo({
                  url: url
                })
                return
              }
            }
          })
        },
        methods: {
          handlerDecryptData(iv,encrypted_data){
            api.wechatDecryptData({
              iv:iv,
              session_key:this.login_info.session_key,
              encrypted_data:encrypted_data
            }).then(result=>{
              console.log('wechatDecryptData result: ',result)
              let data={
                brand_id: this.login_info.brand_id,
                open_id: this.login_info.openid,
                // name: user.nickName,
                // avatar_url: user.avatarUrl,
                // is_vip: "N",
                union_id:result.data.unionid,
              }
              console.log('data',data)
              api.createWxUserV1(data).then(result => {
                console.log('createWxUser result: ', result)
                self.$store.dispatch("setUser", result.data)
              })
            })
          },
          bindGetUserinfo(e) {
            let self = this
            let user = e.mp.detail.userInfo
            if (!user) return

            console.log('bindGetUserinfo e: ',e)
            this.handlerDecryptData(e.target.iv,e.target.encrypted_data)

            self.showGetUserInfoButton = false
          },
          handleCancel() {
            this.showGetUserInfoButton = false
          },
          handleGrid(item) {
            // console.log('id=> ',this.user.id)
            // if (!this.user.id) {
            //     showErrorMsg('请先绑定会员卡或者申请会员卡！')
            //     return
            // }
            if(item.name=='微信会员卡'){
              console.log(this.user)
              if(!this.user.union_id){
                wx.navigateTo({url: 'get_user_info'})
                return
              }
              this.addWxCard()
            }else{
              // this.$store.dispatch("setUser",null)
              // this.$store.dispatch("login",{openid:""})
              wx.navigateTo({url: item.url})
            }
          },
          handleBindCard() {
              //this.addWxCard()
            wx.navigateTo({url: 'bind_member_card'})
          },
          hanldeCoupons() {
            if (!this.user.id) {
              showErrorMsg('请先绑定会员卡或者申请会员卡！')
              return
            }
            wx.navigateTo({url: 'coupons'})
          },
          createNonceStr: function () {
            return Math.random().toString(36).substr(2, 15)
          },
          createTimeStamp: function () {
            return parseInt(new Date().getTime() / 1000) + ''
          },
          createSignature(timestamp, api_ticket, nonce_str, card_id) {
            let array = [timestamp, api_ticket, nonce_str, card_id]
            array.sort()
            let signtrue = ''
            for (var i = 0; i < array.length; i++) {
                signtrue += array[i]
            }
            // for(arr of array){
            //     signtrue += arr
            // }
            console.log('signtrue', signtrue)
            return this.sha1(signtrue)
          },
          sha1: function (s) {
            var data = new Uint8Array(this.encodeUTF8(s))
            var i, j, t;
            var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
            s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
            for (t = new DataView(s.buffer), i = 0; i < l; i++) s[i] = t.getUint32(i << 2);
            s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
            s[l - 1] = data.length << 3;
            var w = [], f = [
                    function () {
                        return m[1] & m[2] | ~m[1] & m[3];
                    },
                    function () {
                        return m[1] ^ m[2] ^ m[3];
                    },
                    function () {
                        return m[1] & m[2] | m[1] & m[3] | m[2] & m[3];
                    },
                    function () {
                        return m[1] ^ m[2] ^ m[3];
                    }
                ], rol = function (n, c) {
                    return n << c | n >>> (32 - c);
                },
                k = [1518500249, 1859775393, -1894007588, -899497514],
                m = [1732584193, -271733879, null, null, -1009589776];
            m[2] = ~m[0], m[3] = ~m[1];
            for (i = 0; i < s.length; i += 16) {
                var o = m.slice(0);
                for (j = 0; j < 80; j++)
                    w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
                        t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
                        m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
                for (j = 0; j < 5; j++) m[j] = m[j] + o[j] | 0;
            }
            ;
            t = new DataView(new Uint32Array(m).buffer);
            for (var i = 0; i < 5; i++) m[i] = t.getUint32(i << 2);

            var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
                return (e < 16 ? "0" : "") + e.toString(16);
            }).join("");

            return hex
          },
          encodeUTF8: function (s) {
            var i, r = [], c, x;
            for (i = 0; i < s.length; i++)
              if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
              else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
              else {
                  if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
                      c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
                          r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
                  else r.push(0xE0 + (c >> 12 & 0xF));
                  r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
              }
            ;
            return r;
          },
          addWxCard: function() {
            let self=this
            console.log(this.user)
            if(this.user.card_id!=""){
              // 已领取微信会员卡
              wx.openCard({
                cardList: [{
                  cardId: this.user.card_id,
                  code: this.user.code
                }],
                success: function(res) {

                }
              })
              return
            }

            let brand_id=this.login_info.brand_id
            let card_id=''
            let user=this.user
            api.findWechatCards({
              brand_id: this.login_info.brand_id,
              status: 'enable'
            }).then(result => {
              if (result.code === 0) {
                if (result.data.data.length === 0) {
                  console.log('未配置启用会员卡')
                  return
                }
                let wxCard = result.data.data[0]
                console.log(wxCard)
                // this.cardId = wxCard.card_id
                card_id=wxCard.card_id
                console.log(card_id)

                api.getWechatCardTicket({
                  brand_id: this.login_info.brand_id
                }).then(result => {
                  if (result.code === 0) {
                    console.log('getWechatCardTicket result',result)
                    //获取随机字符
                    let nonce_str = this.createNonceStr()
                    // //获取时间戳
                    let timestamp = this.createTimeStamp()
                    console.log(card_id)
                    let signature = this.createSignature(timestamp, result.data, nonce_str, card_id)
                    wx.addCard({
                      cardList: [{
                        cardId: card_id,
                        cardExt: '{"nonce_str":"' + nonce_str + '","timestamp":"' + timestamp + '","signature":"' + signature + '"}'
                      }],
                      success: function(res) {
                        console.log('success', res)
                        api.wechatDecryptCode({
                          brand_id: brand_id,
                          decrypt_code:res.cardList[0].code
                        }).then(result => {
                          if (result.code === 0) {
                            // this.openWxCard(this.cardId, result.data)
                            let code=result.code
                            wx.openCard({
                              cardList: [{
                                cardId: card_id,
                                code: result.data
                              }],
                              success: function(res) {
                                console.log('data',data)
                                user.card_id=card_id
                                user.code=code
                                console.log('data',user)
                                self.$store.dispatch("  wx.openCard user",user)
                                let data={
                                  brand_id: brand_id,
                                  open_id: user.open_id,
                                  card_id:card_id,
                                  code:result.data
                                }
                                api.createWxUserV1(data).then(result=>{
                                  console.log('createWxUser', result)
                                })
                              }
                            })
                          } else {
                            console.log('wechatDecryptCode err')
                          }
                        })
                      },
                      fail: function(res) {
                        console.log('fail', res)
                      },
                    })
                  } else {
                    alert('getCardTicket查询失败')
                  }
                })
              }
            })
          },
          testSubmit(e){
              let form_id=e.target.formId
              this.form_id=form_id
              console.log('e',e)
              console.log('form_id',form_id)
              let _access_token = '14_7Y8ojEa-sLkBdDFB4DGrFz4dk9k9VXpPGKYa6aYkSi8TJQVfSc2_730vPYaDm5LWOyfwmQnsvHvtfe35F6TKKdjBonpfeHiHNvX-dJRq_rGKWos0dBWHJA0tPMnOz033jJAJk5vb3BdbGH3uKUYcAIDUEI'
              let url='https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='+_access_token
              let _jsonData = {
                touser: 'o2sD05W9ERpLSQvefZQSe627Ry0Q',
                template_id: "9s8T82Jm-qUb8-7UOMvkWkWlhraI4_TPfoQAsy5pXIE",
                form_id: 'wx10144548420876f86e07fd3e1340007710',
                page: "pages/user/transaction_record",
                data: {
                  "keyword1": { "value": "测试数据一"},
                  "keyword2": { "value": "测试数据二", "color": "#173177" },
                  "keyword3": { "value": "测试数据三", "color": "#173177" },
                  "keyword4": { "value": "测试数据四", "color": "#173177" },
                }
              }
              wx.request({
                  url: url,
                  data: _jsonData,
                  method: 'POST',
                  success: function (res) {
                    console.log(res)
                  },
                  fail: function (err) {
                    console.log('request fail ', err);
                  },
                  complete: function (res) {
                    console.log("request completed!");
                  }
              })
          },
          clean(){
            this.$store.dispatch("setUser",null)
            this.$store.dispatch("login",null)
            this.$store.dispatch("setWechatCallback",null)
            // wx.navigateTo({url: 'get_user_info'})
          },
          skip(){
            // 回调页面
            wx.redirectTo({
              url: '../home/index'
            })
          },
          receipt(){
            // 回调页面
            wx.navigateTo({
              url: 'micro_pay?shop_id=2&scene=2'
            })
          },
          check_in(){
            // 回调页面
            wx.navigateTo({
              url: 'check_in'
            })
          },
          navigateTo(url){
            // 回调页面
            wx.navigateTo({
              url: url
            })
          },
          activeWxCard(){
            let url = "wechat_card_activate?card_id=p02Lz1Z8JoDkwrK2fOVtzso-0qhw&encrypt_code=Wp5c4jMuq9S2jhnJAUdIJvAEL5BWm0AQz6ct0cE4CiA%3D&openid=o02Lz1cOZk6Vumrb91y7-qRq9bxQ"
            // 回调页面
            wx.navigateTo({
              url: url
            })
          },
        }
    }
</script>

<style scoped>
    .mem_btn {
        height: 45px;
        line-height: 45px;
        text-align: center;
        background: black;
        color: white;
        margin-top: 5px;
    }

    .user {
        height: 60px;
    }

    .userInfo {
        height: 60px;
        line-height: 30px;
        text-align: center;
    }

    .coupons {
        position: relative;
    }

    .arrow {
        position: absolute;
        right: 20px;
        bottom: 0;
    }

    .grids {
        border-top: 1px solid #d9d9d9;
        border-left: 1px solid #d9d9d9;
        overflow: hidden
    }

    .grids-item {
        position: relative;
        float: left;
        padding: 20px 10px;
        width: 33.33333333%;
        box-sizing: border-box;
        border-right: 1px solid #d9d9d9;
        border-bottom: 1px solid #d9d9d9
    }

    .grid_active {
        background-color: #ececec
    }

    .zan-icon {
        display: block;
        width: 28px;
        height: 28px;
        font-size: 24px;
        margin: 5px auto
    }

    .grid_label {
        margin-top: 5px;
        display: block;
        text-align: center;
        color: #000;
        font-size: 18px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden
    }

    .card {
        position: relative;
        margin: 5px auto;
        width: 90%;
        height: 170px;
        border-radius: 10px;
        background-size: 100% 100%;
    }

    .card-num {
        font-size: 16px;
        color: #FFFAFA;
        position: absolute;
        bottom: 10px;
        left: 10px;
    }

    .addcard-btn {
        font-size: 16px;
        color: #FFFAFA;
        position: absolute;
        bottom: 10px;
        right: 10px;
        text-decoration:underline;
    }

    .dialog-box {
        position: absolute;
        z-index: 9999;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: justify;
        background-color: rgba(0, 0, 0, 0.7);
    }

    .dialog-body {
        width: 300px;
        height: 160px;
        background: #fff;
    }

    .confirm-btn {
        border-radius: 0;
        width: 100px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #4b0;
        color: #fff;
        float: right;
        margin: 0 10px 0 10px;
    }

    .cancel-btn {
        width: 100px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #DBDBDB;
        color: #737373;
        float: right;
        border-radius: 0;
    }

    .drawer_screen {
        width: 100%;
        height: 100%;
        position: fixed;
        top: 0;
        left: 0;
        z-index: 1000;
        background: #000;
        opacity: 0.5;
        overflow: hidden;
    }

    .drawer_box_ad {
        margin-left: 6%;
        width: 88%;
        position: fixed;
        top: 20%;
        z-index: 1001;
        background: #C45E4F;
        border-radius: 10px;
    }

    .drawer_content_ad {
        margin: 20px;
        padding-bottom: 20px;
        padding-top: 10px;
        background: #fff;
    }

    .coupon-top {
        width: 100%;
        height: 50px;
        line-height: 50px;
        text-align: center;
        border-radius: 50%;
        background: #F2E5DC;
        font-weight: bold;
    }

    .receive-coupon {
        width: 140px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        color: white;
        background: #EC4A48;
        border-radius: 20px;
        margin: auto;
    }

    .close-coupon {
        font-size: 35px;
        position: absolute;
        bottom: -40px;
        left: 50%;
        transform: translate(-50%);
        color: #fff;
    }
</style>
